﻿
using Microsoft.Phone.Controls;
using System;
using System.Windows;
using System.Windows.Controls;

namespace EmperialApps.WeatherSpark {

    public class FixedAutoCompleteBox : AutoCompleteBox {

        public double PopupVerticalOffset { get; set; }

        private TextBox _text;

        public override void OnApplyTemplate( ) {
            base.OnApplyTemplate( );

            this._text = (TextBox)this.GetTemplateChild( "Text" );
        }

        protected override void OnDropDownOpening( RoutedPropertyChangingEventArgs<bool> e ) {
            // Block attempts by base implementation to show popup when focus has changed.
            bool canOpen = this._text.IsEnabled && this.HasFocus( );
            e.Cancel = !canOpen;

            base.OnDropDownOpening( e );
        }

        protected override void OnDropDownClosed( RoutedPropertyChangedEventArgs<bool> e ) {
            base.OnDropDownClosed( e );

            // Temporarily disable text input, so that base implementation cannot steal focus.
            if( this._text.IsEnabled ) {
                this._text.IsEnabled = false;
                this.Dispatcher.BeginInvoke( new Action( ( ) => this._text.IsEnabled = true ) );
            }
        }

    }

}
